package cn.liujinnan.tetris.utils;/*
 * Copyright(c) 2021 by liujinnan.cn All rights Reserved.
 */

import net.sf.cglib.beans.BeanCopier;

import java.util.ArrayList;
import java.util.List;

/*
 * Copyright(c) 2021 by liujinnan.cn All rights Reserved.
 */

/**
 * 二维数组
 * @author LiuJinan
 * @date 2021-08-21 01:26
 */
public class TwoDimensionalArray<T> {


    private final List<List<T>> data;

    /**
     * 二维数组x
     */
    private final Integer maxX;

    private final Integer maxY;

    /**
     * @param maxX
     * @param maxY
     */
    public TwoDimensionalArray(int maxX, int maxY){
        this.maxX = maxX;
        this.maxY = maxY;
        data = new ArrayList<>();
        for (int i = 0; i < maxY; i++) {
            for (int i1 = 0; i1 < maxX; i1++) {
                List<T> row = new ArrayList<>(maxY);
                data.add(row);
            }
        }


    }

    public T getCell(int x, int y) {
        checkBounds(x, y);
        List<T> row = data.get(y);
        return row.get(x);
    }

    public void setCell(int x, int y, T newCell)  {
        checkBounds(x, y);
        List<T> row = data.get(y);
        try {
            BeanCopier beanCopier = BeanCopier.create(newCell.getClass(), newCell.getClass(), false);
            beanCopier.copy(newCell, row.get(x), null);
        } catch (Exception e) {
        }
    }

    /**
     * 检查数组是否越界，越界抛出异常
     * @param x
     * @param y
     */
    private void checkBounds(int x, int y) {
        if (y > maxY || x>maxX) {
            throw new IndexOutOfBoundsException();
        }
    }
}
